package com.pronhub.cloud.shop.service.imp;

import com.pronhub.cloud.shop.redis.MyRedisTemplate;
import com.pronhub.shop.cloud.BussinessException;
import com.pronhub.cloud.shop.mapper.UserMapper;
import com.pronhub.cloud.shop.msg.MemberServerCodeMsg;
import com.pronhub.cloud.shop.redis.MemberServerKeyPrefix;
import com.pronhub.cloud.shop.service.IUserService;
import com.pronhub.cloud.shop.util.MD5Util;
import com.pronhub.cloud.shop.web.vo.LoginVO;
import com.pronhub.cloud.shop.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    //操作MySql数据库的11
    @Autowired
    private UserMapper userMapper;

    //操作Redis的
    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Override
    public User find(Long id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public String login(LoginVO loginVO) {


        User user = this.find(Long.parseLong(loginVO.getUsername()));
        //检查账号是否存在
        if (user == null){
            throw new BussinessException(MemberServerCodeMsg.LOGIN_ERROR_NULLUSER);
        }
        //对比从数据库查出来的密码还有传过来的密码明文对比
        String pass = MD5Util.encoding(loginVO.getPassword(), user.getSalt());
        if (!pass.equals(user.getPassword())){
            throw new BussinessException(MemberServerCodeMsg.LOGIN_ERROR);
        }
        //生成token
       //todo 集成Redis+Session的登录方式
        String token = creatToken(user);
        return token;
    }


    public String creatToken(User user){
        //token的创建
        String token = UUID.randomUUID().toString().replace("-", "");
        //吧User存到redis里面
        myRedisTemplate.set(MemberServerKeyPrefix.USER_TOKEN,token,user);
        //完整的一个key是下面的
        String reallyKey = MemberServerKeyPrefix.USER_TOKEN.getPrefix() + token;
        return token;
    }

    //更新Token的数据
    @Override
    public Boolean refreshToken(String token) {
        //做的恶意防刷  去Redis查找相关的是否存在 存在就给更新Cookie
        if (myRedisTemplate.exists(MemberServerKeyPrefix.USER_TOKEN,token)){
            Long result = myRedisTemplate.expire(MemberServerKeyPrefix.USER_TOKEN, token, 1800);
            //result==1说明设置成功，如果result==0说明没有设置成功
            return result==1;
        }
        return false;
    }

    @Override
    public User getUserByToken(String token) {
        User user = myRedisTemplate.get(MemberServerKeyPrefix.USER_TOKEN, token, User.class);
        return user;
    }


  /*  @Override
  InitializingBean
    public void afterPropertiesSet() throws Exception {
        myRedisTemplate.get(null,"",Object.class);
        System.err.println("233===>"+myRedisTemplate);
    }*/
}
